package com.example.hospitalsystem.handle;

import com.example.hospitalsystem.result.Result;
import com.example.hospitalsystem.result.ResultCodeEnum;
import com.example.hospitalsystem.utils.JwtHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{
        //
        String token=request.getHeader("Authorization");
        if(StringUtils.isEmpty(token)|| jwtHelper.isExpiration(token)){
            Result<Object> result= Result.build(null, ResultCodeEnum.NOTLOGIN);
            //该对象用于将result对象转换位json字符串
            ObjectMapper objectMapper=new ObjectMapper();
            String json=objectMapper.writeValueAsString(result);
            //设置响应的content-type为JSON
            response.setContentType("/application/json");
            //设置响应的字符编码为UTF-8
            response.setCharacterEncoding("UTF-8");
            //将json字符串写入响应的输出流
            response.getWriter().print(json);
            //拦截
            return false;
        }else{
            //放行
            return true;
    }
    }
}
